<?php
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Help Desk
 * @version 	1.0
 * @author 		Kurosaki <kurosaki@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
require_once (_PS_CLASS_DIR_ . 'FrontController.php');
include_once(dirname(__FILE__)."/../Zadmindepartment.php");
include_once(dirname(__FILE__)."/../ZadminPriority.php");
include_once(dirname(__FILE__)."/../ZadminStatus.php");
include_once(dirname(__FILE__)."/../classes/ZticketObject.php");


class ZhelpdeskPostTicketController extends FrontControllerCore {
	private $complete = null;
    public function setMedia() {
    	parent::setMedia();
    	Tools::addCSS(_MODULE_DIR_.'/zhelpdesk/css/post-ticket.css');
    	Tools::addJS(__PS_BASE_URI__.'js/tiny_mce/tiny_mce.js');
    	Tools::addJS(_MODULE_DIR_.'/zhelpdesk/js/post-ticket.js');
        
    }

    /**
     * display content
     */
    public function displayContent() {
    	/*for Editor MCE*/
    	$iso = Language::getIsoById((int)(self::$cookie->id_lang));
		$isoTinyMCE = (file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en');
		$ad = dirname($_SERVER["PHP_SELF"]);
		/*end for Editor MCE*/
		
		$listDepartments = ZDepartmentObject::getAllDepartMent(self::$cookie->id_lang,true);
		$listDayWorking = explode(',',Configuration::get ('WORKING_DAY'));
		$timeDay = array (
			'Monday' => 0,
			'Tuesday' => 1,
			'Wednesday' => 2,
			'Thursday' => 3,
			'Friday' => 4,
			'Saturday' => 5,
			'Sunday' => 6,
		);
		$day = date("l");
		
		$statusTime = 0;
		if (in_array($day, $listDayWorking) ) {
			$time = Configuration::get('WORKING_TIME_'.$day);
			$times = explode (';',$time);
			$timeCurent = time ();
			$time = explode ('-',$times[0]);
			
			if ($timeCurent >= strtotime($time[0]) && $timeCurent <= strtotime($time[1])) {
				$statusTime = 1;
			}
			$time = explode ('-',$times[1]);
			if ($timeCurent >= strtotime($time[0]) && $timeCurent <= strtotime($time[1])) {
				$statusTime = 1;
			}
		}
		
		$temp = '';
		$kcTime = array ();
		$listTimeWorkingDay = array (); 
    	foreach ($listDayWorking as $k=>$item) {
    		$times = explode (';',Configuration::get('WORKING_TIME_'.$item));
    		$time =  explode ('-',$times[0]);
    		
    		if (strtotime($time[0]) != strtotime($time[1])) 
    			$temp .= $time[0]." - ".$time[1];
    		$time =  explode ('-',$times[1]);
    		if (strtotime($time[0]) != strtotime($time[1])) {
    			if ($temp!='')
    				$temp .= ' | '.$time[0]." - ".$time[1];
    		}
    		$kcTime2 = strtotime($time[0]) - strtotime($time[1]);
    		$listTimeWorkingDay[$item] = $temp;
    		if ($temp!='') {
    			$kcTime[$temp][] = $item;
    		}
    		$temp='';
		}
		$resultTime = array ();
		$timeTo = "";
		$timeFrom = "";
		$qkTime = array ();
		$end = "";
		foreach ($listTimeWorkingDay as $k=>$item) {
 			if ($timeFrom == "") {
				$timeTo = $k;
				$timeFrom = $k;
			} else {
				if ($item == $listTimeWorkingDay[$timeTo]) {
					if (($timeDay[$timeFrom]+1) == $timeDay[$k] ) {
						$timeFrom = $k;
					} else {
						if ($timeTo == $timeFrom) {
							$qkTime[$timeTo] = $listTimeWorkingDay[$timeTo];
							$timeTo = $k;
							$timeFrom = $k;
							$end = $k;
						} else {
							$qkTime[$timeTo."-".$timeFrom] = $listTimeWorkingDay[$timeTo];
							$timeTo = $k;
							$timeFrom = $k;
							$end = $k;
						}
					}
				} else {
					if ($timeTo == $timeFrom) {
						$qkTime[$timeTo] = $listTimeWorkingDay[$timeTo];
						$timeTo = $k;
						$timeFrom = $k;
						$end = $k;
					} else {
						$qkTime[$timeTo."-".$timeFrom] = $listTimeWorkingDay[$timeTo];
						$timeTo = $k;
						$timeFrom = $k;
						$end = $k;
					}
				}
			}
		}
		if ($timeTo == $timeFrom)
			$qkTime[$timeFrom] = $listTimeWorkingDay[$timeFrom];
		else 
			$qkTime[$timeTo."-".$timeFrom] = $listTimeWorkingDay[$timeTo];
		$orders = ((self::$cookie->isLogged())?OrderCore::getCustomerOrders (self::$cookie->id_customer):'');
		$prioritys = ZpriorityObject::getAllPriority (self::$cookie->id_lang);
    	self::$smarty->assign(array(
			'_PS_IMG_' => _PS_IMG_,
    		'ad' => $ad,
    		'iso' => $iso,
    		'pathCSS' => _THEME_CSS_DIR_,
    		'pathPage' => Tools::getShopDomain(true).__PS_BASE_URI__.'modules/zhelpdesk/',
    		'login' =>  self::$cookie->isLogged(),
    		'listDepartments' => $listDepartments,
    		'listDayWorking' => $kcTime,
    		'prioritys' => $prioritys,
    		'orders' => $orders,
    		'timezone' => Configuration::get ('PS_TIMEZONE'),
    		'statusTime' => $statusTime,
    		'timeDay' => $timeDay,
    		'zdate_now' => date('l jS \of F Y h:i A'),
    		'qkTime' => $qkTime
		));
        parent::displayContent();
        self::$smarty->display(_PS_MODULE_DIR_ . 'zhelpdesk/themes/post-ticket.tpl');
    }
    
    
    
	public function preProcess() {
		if (Tools::isSubmit('submitNewTicket')) {
			$obj = new ZTicketObject ();
			$obj->id_zhelpdesk_department = Tools::getValue ('id_department');
			$department = new ZDepartmentObject($obj->id_zhelpdesk_department);
			$obj->id_staff = $department->id_moderator;
			$obj->id_zhelpdesk_ticket_priority = Tools::getValue ('id_zhelpdesk_ticket_priority');
			$code = ZTicketObject::genCode(8);
			while (ZTicketObject::testSameCode($code)!=0) {
				$code = ZTicketObject::genCode(8);				
			}
			$obj->ticket_code =  $code;// create code
			$id_customer = (!$id_customer = (int)self::$cookie->id_customer) ? false : (int)self::$cookie->id_customer;
			$obj->id_customer = $id_customer;
			$obj->id_zhelpdesk_ticket_status = 1;
			if (Tools::getValue('content')=='') 
					$this->errors[] = Tools::displayError('This <b>content</b> is require.');
			if (self::$cookie->isLogged()==0) {
				if (Tools::getValue('name')=='') 
					$this->errors[] = Tools::displayError('This <b>name</b> is require.');
				else 
					$obj->name_customer = Tools::getValue ('name');
				
				if (!Validate::isEmail($email = Tools::getValue('email')) OR empty($email))
					$this->errors[] = Tools::displayError('This <b>email</b> is require.');
				else 
					$obj->email_customer = Tools::getValue ('email');
			} else {
				$obj->id_order =  Tools::getValue ('order');
				$customer = new CustomerCore($id_customer);
				$obj->email_customer = $customer->email;
				$obj->name_customer = $customer->firstname." ".$customer->lastname;
			}
			if (Tools::getValue('subject')=='')
				$this->errors[] = Tools::displayError('This <b>subject</b> is require');
			else 
				$obj->subject = Tools::getValue ('subject');
			$this->errors = array_unique(array_merge($this->errors, $obj->validateControler()));
			if (empty($this->errors)) {
				
				if (!$obj->save ()) {
					$this->errors[] = Tools::displayError('Don\'t save please come back in few minute');
				}
				else {
					$content = Tools::getValue ('content');
					if ($fileimg = $_FILES['attached_files']['name']) {
						$obj->setMessageForTicket ($content,$fileimg);
					} else 
						$obj->setMessageForTicket ($content);
						
					/* ----getway send mail when add new ticket------------- */
					$employee = new EmployeeCore ($obj->id_staff);
					$name = $employee->firstname." ".$employee->lastname;
					$textbody = Configuration::get('NEW_TICKET_TEMPLATE_FOR_STAFF',Configuration::get('PS_LANG_DEFAULT'));
					
					if ($textbody == '')
						$textbody = '<p>Hi {name_moderator}, you get a ticket is sent from customer name {name_customer}, email {email_customer}</p><p>{content}</p><p>Please reply to this email within 24 hours</p>';
					
					$words = array (
						'{name_moderator}' => $name,
						'{name_customer}' => $obj->name_customer,
						'{email_customer}' => $obj->email_customer,
						'{content}' => $content,
						'{subject}' => $obj->subject
					);
					
					$rs = ZticketObject::sendMailTo ($employee->email,$name,$obj->subject,$textbody,$words);
					/* ----getway send mail when add new ticket------------- */
					
					$this->complete =1;
				}
			}
		}
		
		self::$smarty->assign(array(
			'hasError' => !empty($this->errors),
			'errors' => $this->errors,
			'complete' => $this->complete
		));
		
		parent::preProcess();
	}
	public function process() {
		
		parent::process();
	}
}
